package com.lewis.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lewis.core.annotation.DataSource;
import com.lewis.core.constant.Constants;
import com.lewis.core.constant.UserConstants;
import com.lewis.core.utils.RedisUtil;
import com.lewis.core.base.text.Convert;
import com.lewis.core.enums.DataSourceType;
import com.lewis.core.exception.CustomException;
import com.lewis.core.utils.DateUtil;
import com.lewis.core.utils.StringUtil;
import com.lewis.system.service.ISysConfigService;
import com.lewis.system.entity.SysConfig;
import com.lewis.system.mapper.SysConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 参数配置 服务层实现
 *
 * @author Lewis
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {

    @Autowired
    private SysConfigMapper configMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    /**
     * 查询参数配置信息
     *
     * @param id 参数配置ID
     * @return 参数配置信息
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public SysConfig selectConfigById(Long id) {
        return configMapper.selectById(id);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = Convert.toStr(redisUtil.getCacheObject(getCacheKey(configKey)));
        if (StringUtil.isNotEmpty(configValue)) {
            return configValue;
        }
        SysConfig retConfig = configMapper.selectOne(
                new LambdaQueryWrapper<SysConfig>()
                        .eq(SysConfig::getConfigKey, configKey)
        );
        if (StringUtil.isNotNull(retConfig)) {
            redisUtil.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtil.EMPTY;
    }

    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaOnOff() {
        String captchaOnOff = selectConfigByKey("sys.account.captchaOnOff");
        if (StringUtil.isEmpty(captchaOnOff)) {
            return true;
        }
        return Convert.toBool(captchaOnOff);
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfig> selectConfigList(SysConfig config) {

        LambdaQueryWrapper<SysConfig> lqw = new LambdaQueryWrapper<SysConfig>()
                .eq(StringUtil.isNotEmpty(config.getConfigType()), SysConfig::getConfigType, config.getConfigType())
                .like(StringUtil.isNotEmpty(config.getConfigName()), SysConfig::getConfigName, config.getConfigName())
                .like(StringUtil.isNotEmpty(config.getConfigKey()), SysConfig::getConfigKey, config.getConfigKey());

        Map<String, Object> params = config.getParams();
        if (params != null) {
            Object beginTime = config.getParams().get("beginTime");
            if (beginTime != null) {
                lqw.ge(StringUtil.isNotEmpty(String.valueOf(DateUtil.parseDate(config.getParams().get("beginTime")))), SysConfig::getCreateTime, String.valueOf(DateUtil.parseDate(config.getParams().get("beginTime"))));
            }
            Object endTime = config.getParams().get("endTime");
            if (endTime != null) {
                lqw.le(StringUtil.isNotEmpty(String.valueOf(DateUtil.parseDate(config.getParams().get("endTime")))), SysConfig::getCreateTime, String.valueOf(DateUtil.parseDate(config.getParams().get("endTime"))));
            }
        }

        return configMapper.selectList(lqw);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysConfig config) {
        int row = configMapper.insert(config);
        if (row > 0) {
            redisUtil.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysConfig config) {
        int row = configMapper.updateById(config);
        if (row > 0) {
            redisUtil.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量删除参数信息
     *
     * @param ids 需要删除的参数ID
     * @return 结果
     */
    @Override
    public void deleteConfigByIds(Long[] ids) {
        for (Long id : ids) {
            SysConfig config = selectConfigById(id);
            if (StringUtil.equals(UserConstants.YES, config.getConfigType())) {
                throw new CustomException(String.format("内置参数【%1$s】不能删除 " , config.getConfigKey()));
            }
            configMapper.deleteById(id);
            redisUtil.deleteObject(getCacheKey(config.getConfigKey()));
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<SysConfig> configsList = configMapper.selectList(null);
        for (SysConfig config : configsList) {
            redisUtil.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        Collection<String> keys = redisUtil.keys(Constants.SYS_CONFIG_KEY + "*");
        redisUtil.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public String checkConfigKeyUnique(SysConfig config) {
        Long id = StringUtil.isNull(config.getId()) ? -1L : config.getId();
        SysConfig info = configMapper.selectOne(
                new LambdaQueryWrapper<SysConfig>()
                        .eq(SysConfig::getConfigKey, config.getConfigKey())
                        .last("limit 1")
        );
        if (StringUtil.isNotNull(info) && info.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return Constants.SYS_CONFIG_KEY + configKey;
    }
}
